/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package foxmob.mlts.view.student;

import foxmob.mlts.model.MultipleFillInBlankQuestion;
import foxmob.mlts.viewcontroller.student.QuestionPaperForm;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyListener;
import javax.swing.event.DocumentEvent;
import javax.swing.text.Document;

/**
 *
 * @author zpf16z
 */
public class MultipleFillInJPanel extends javax.swing.JPanel implements KeyListener{

    String question = "This is a __, and I ________ not like _.";
    private ArrayList<String> studentAnswer = new ArrayList<String>();
    private int countAnswer = -1;
    private int countQuestion = 0;
    private ArrayList<JTextField> textField = new ArrayList<JTextField>();
    private boolean state = false;
    private MultipleFillInBlankQuestion multipleFillInBlankQuestionq = new MultipleFillInBlankQuestion();
    
    /**
     * Creates new form MultipleFillInJPanel
     */
    public MultipleFillInJPanel() {
        initComponents();
        //setQuestion(question);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelBlanks = new javax.swing.JLabel();
        jLabelQuestionID = new javax.swing.JLabel();

        setMaximumSize(new java.awt.Dimension(1232312, 123123123));
        setMinimumSize(new java.awt.Dimension(240, 78));
        setPreferredSize(new java.awt.Dimension(120, 78));
        setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.LINE_AXIS));

        jLabelBlanks.setText("                                 ");
        add(jLabelBlanks);

        jLabelQuestionID.setText("  Q1.");
        add(jLabelQuestionID);
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabelBlanks;
    private javax.swing.JLabel jLabelQuestionID;
    // End of variables declaration//GEN-END:variables

    private void setQuestion(String question) {
        char[] q = question.toCharArray();
        int length = question.length();
        for (int i = 0; i < length;) {
            if (i < length && q[i] == '_') {
                countAnswer++;
                final JTextField tf = new JTextField();
                textField.add(tf);
                studentAnswer.add("0");
                int wide = 0;
                while (q[i] == '_') {
                    wide++;
                    i++;
                }
                tf.setColumns(wide * 10);
//                tf.addActionListener(new ActionListener() {
//                    public void actionPerformed(ActionEvent e) {
//                        System.out.println("Text=" + tf.getText());
//                        setAnswer(textField.indexOf(tf), tf.getText());
//                    }
//
//
//                });

                Document dt = tf.getDocument();
                dt.addDocumentListener(new javax.swing.event.DocumentListener() {
                    /**
                     * Gives notification that an attribute or set of attributes
                     * changed.
                     *
                     * @param e the document event
                     */
                    public void changedUpdate(DocumentEvent e) {
                        // TODO 自动生成方法存根
                        System.out.println("changed");
                    }

                    /**
                     * Gives notification that there was an insert into the
                     * document. The range given by the DocumentEvent bounds the
                     * freshly inserted region.
                     *
                     * @param e the document event
                     */
                    public void insertUpdate(DocumentEvent e) {
                        // TODO 自动生成方法存根
                        System.out.println("insert!");
                    }

                    @Override
                    public void removeUpdate(DocumentEvent de) {
                        System.out.println("remove");
                    }

                    /**
                     * Gives notification that a portion of the document has
                     * been removed. The range is given in terms of what the
                     * view last saw (that is, before updating sticky
                     * positions).
                     *
                     * @param e the document event
                     */
                });
//                
                Dimension d = new Dimension();
                d.setSize(1, 28);
                tf.setPreferredSize(d);
                tf.setMaximumSize(d);
                this.add(tf);
                this.repaint();
            } else {
                JLabel lable = new JLabel();
                int wide = 0;
                String temp = "";
                while (i < length && q[i] != '_') {
                    temp += q[i];
                    wide++;
                    i++;
                }
                if (temp != null) {
                    System.out.println(temp);
                    lable.setText(temp);
                    this.add(lable);
                }
            }
        }
    }
    private void setAnswer(int i, String answer) {
//        fib = (FillInTheBlanksQuestion) QuestionPaperForm.testRecord.getAllQuestions().get(this.questionCount - 1);
//        fib.setStudentAnswer(this.jTextFieldAnswer.getText());
        studentAnswer.set(i, answer);
        //studentAnswer.toArray(temp);
        String[] temp = studentAnswer.toArray(new String[studentAnswer.size()]);
        this.multipleFillInBlankQuestionq.setStudentAnswer(temp);
        //QuestionPaperForm.testRecord.getAllQuestions().get(countQuestion -1).setStudentAnswer(temp);
        System.out.println(studentAnswer.toString());
        setQuestionFinished();
        // Save answers to File.
    }

    private void setQuestionFinished() {
//        if (this.state) {
//            if (this.jTextFieldAnswer.getText().length() == 0) {
//                this.state = false;
//                QuestionPaperForm.finishedQuestions--;
//            }
//        } else {
//            if (this.jTextFieldAnswer.getText().length() > 0) {   
//                this.state = true;
//                QuestionPaperForm.finishedQuestions++;
//            }
//        }
        if(this.state != true){
            QuestionPaperForm.finishedQuestions++;
        }
        this.state = true;
    }

    public void loadQuestion(MultipleFillInBlankQuestion question, int count) {
        this.multipleFillInBlankQuestionq = question;
        this.countQuestion = count;
        this.jLabelQuestionID.setText("Q" + Integer.toString(count) + ":  ");
        char[] q = question.getQuestionText().toCharArray();
        for (int i = 0; i < q.length;) {
            if (i < q.length && q[i] == '_') {
                countAnswer ++;
                final JTextField tf = new JTextField();
                textField.add(tf);
                studentAnswer.add("0");
                int wide = 0;
                while (q[i] == '_') {
                    wide++;
                    i++;
                }
                tf.setColumns(wide * 10);
                tf.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
//                        System.out.println("Text=" + tf.getText());
//                        setAnswer(textField.indexOf(tf), tf.getText());
                    }
                });
                
                                Document dt = tf.getDocument();
                dt.addDocumentListener(new javax.swing.event.DocumentListener() {
                    /**
                     * Gives notification that an attribute or set of attributes
                     * changed.
                     *
                     * @param e the document event
                     */
                    public void changedUpdate(DocumentEvent e) {
                        // TODO 自动生成方法存根
                        System.out.println("changed");
                    }

                    /**
                     * Gives notification that there was an insert into the
                     * document. The range given by the DocumentEvent bounds the
                     * freshly inserted region.
                     *
                     * @param e the document event
                     */
                    public void insertUpdate(DocumentEvent e) {
                        // TODO 自动生成方法存根
                        System.out.println("insert!");
                        System.out.println("Text=" + tf.getText());
                        setAnswer(textField.indexOf(tf), tf.getText());
                    }

                    @Override
                    public void removeUpdate(DocumentEvent de) {
                        System.out.println("remove");
                    }

                    /**
                     * Gives notification that a portion of the document has
                     * been removed. The range is given in terms of what the
                     * view last saw (that is, before updating sticky
                     * positions).
                     *
                     * @param e the document event
                     */
                });
                
                //tf.addKeyListener(new MultipleFillInJPanel_tf_keyAdapter(this));
                
                Dimension d = new Dimension();
                d.setSize(1, 28);
                tf.setPreferredSize(d);
                tf.setMaximumSize(d);
                this.add(tf);
                this.repaint();
            } else {
                JLabel lable = new JLabel();
                int wide = 0;
                String temp = "";
                while (i < q.length && q[i] != '_') {
                    temp += q[i];
                    wide++;
                    i++;
                }
                if (temp != null) {
                    System.out.println(temp);
                    lable.setText(temp);
                    this.add(lable);
                }
            }
        }
    }
    public void keyReleased(KeyEvent e) {
        System.out.println("Click!");
    }

    @Override
    public void keyTyped(KeyEvent ke) {
        System.out.println("keyTyped");
    }

    @Override
    public void keyPressed(KeyEvent ke) {
        System.out.println("keyPressed");
        //throw new UnsupportedOperationException("Not supported yet.");
    }
}
